import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
//import java.text.SimpleDateFormat;



public class ReadFlight {
	private static String flightFile = "/home/hnikoue/Documents/Sydney/Data/FIDS_FLIGHTS/FACT_FIDS_FLIGHTS-2012.txt";
//	private int MAXNBFLIGHTS = 516;//half the number of lines
//	private int MAXNBLINES = 4*MAXNBFLIGHTS;
	private BinaryHeap<Flight> flightsSchedule = null;
	private static int NUMBER_ELTS_LINE = 40; //number of elements per line in flightFile. It's really 81, I am being generous
	private LocalArrTime dayOfExtraction; //day of the test from which to extract data 
	private String ignoreString= "FLIGHT_DATETIME_ABLOCK";
	protected int pos = 1;//order of processing
	protected int countLines = 0;
	protected int percentProgress =0;
	protected Flight previousStoredFlight = null;
	private void parseFlight(){
		
		File file = new File(flightFile);
		createFlightQueue();//create a priority queue of all the flights
		if(file.isFile()){
			BufferedReader buf = null;
			try {
				buf = new BufferedReader(new FileReader(flightFile));
				String sCurrentLine ;
				while(((sCurrentLine = buf.readLine()) != null) ){
					
					addFlight2Queue(sCurrentLine);
				}
			} catch (IOException e1) {
				e1.printStackTrace();
			}finally{
				try{
					if (buf != null)buf.close();
				} catch (IOException ex) {
					ex.printStackTrace();
				}
				
			}

		}
	}
	
	/**
	 * Extract relevant flight information from the current line and add the extracted flight to flight schedule
	 * flightSchedule is a binary heap of LocalArrTime, the keys are ordinal numbers
	 * info. extracted: leg,gate,timeOfArrival[BlockTime] and flightID
	 * @param sCurrentLine
	 */
	private void addFlight2Queue(String sCurrentLine) {
		Flight flight2Add;
		String[] flightElements = sCurrentLine.split(",");
		LocalArrTime currentTime;
		int gateNum;
		//format of the date is dd/MM/yyyy (h)h:mm:ss aa"
		
		if(flightElements.length >= NUMBER_ELTS_LINE ){
			if(flightElements[0].compareTo(ignoreString)!=0){
				countLines++;
//				if(countLines%(2*28605) ==0){
//					System.out.println("ReadFlight Status: "+ percentProgress+"%");
//					percentProgress += 10;
//				}
				int day,month,year,hour,minute,second;
				String flightID, gate,timeStr;
				
				timeStr = flightElements[0];
				String leg = flightElements[11];
				if(leg.charAt(0)=='D'){
					return;
				}
				//process gate information
				if(flightElements[24].charAt(0)=='A'||flightElements[24].charAt(0)=='a'){
					gate = flightElements[24].substring(1);
					try{
						gateNum = Integer.parseInt(gate);
					}catch(NumberFormatException e){
						return;
					}
					if(gateNum<50)
						return;
					gate = "gate"+gate;
				}else if(flightElements[24].charAt(0)>65){
					return;
				}else{
					try{
						gateNum = Integer.parseInt(flightElements[24]);
					}catch(NumberFormatException e){
						return;
					}
					if(gateNum<50)
						return;
					gate = "gate"+flightElements[24];//concatenate to have the same format as in the timeAtImmi and time2Immi files
				}
				
				flightID = flightElements[10];
				
				//Extract the time
				String[] times = timeStr.split(" ");
				String[] dMY = times[0].split("/");//day month year
				day = Integer.parseInt(dMY[0]);
				month = Integer.parseInt(dMY[1]);
				year = Integer.parseInt(dMY[2]);
				if(times.length>1){
					String[] hms = times[1].split(":");//hour minute second
					if(times[2].compareTo("AM")==0){
						hour = Integer.parseInt(hms[0]);
					}else{
						hour = Integer.parseInt(hms[0])+12;
					}
					minute = Integer.parseInt(hms[1]);
					second = Integer.parseInt(hms[2]);
					 currentTime = new LocalArrTime(day,month,year,hour,minute,second);
					

				}else{
//					System.out.println("The string is not formatted correctly");
					currentTime = new LocalArrTime(day,month,year);
				}
					//LocalArrTime currentDay = newLocalArrTime(day,month,year);
					//Make sure all elements we add to the heap are on our day of interest
					if (dayOfExtraction.getDay() == currentTime.getDay() && dayOfExtraction.getMonth() == currentTime.getMonth()){
							flight2Add = new Flight(flightID,gate,currentTime);
							//Add the flight to the binary tree if the previous flight does not have the same id
							if(previousStoredFlight ==null || 
									previousStoredFlight.compareTo(flight2Add)!=0 || previousStoredFlight.getGate().equals(gate) && !previousStoredFlight.getFlightID().equals(flight2Add.getFlightID())){
								flight2Add.setTagID(pos++);
								flightsSchedule.add(flight2Add);
								previousStoredFlight = flight2Add;
							}
					}
				
			}
		}
		
	}
	private void createFlightQueue() {
		flightsSchedule = new BinaryHeap<Flight>(Flight.class);
	}

	public ReadFlight(LocalArrTime dayOfInterest){
		dayOfExtraction = dayOfInterest;
		parseFlight();
	}
	public BinaryHeap<Flight> getFlight(){
		if(flightsSchedule == null)
			parseFlight();
		return flightsSchedule;
	}


}